<template>
    <div v-loading="loading"
    element-loading-text="拼命加载中">
        <el-button type="primary" @click="back">{{ title }}</el-button>
        <el-button type="success" :disabled="isDisabled" @click="download(filename)">下载</el-button>
        <div ref="word" class="docWrap"></div>
        <canvas v-for="num in numPages" :key="num" :id="'canvas_'+num" class="canvas"></canvas>
    </div>
</template>
<script>
let docxx = require('docx-preview');
import * as PDFJS from 'pdfjs-dist/legacy/build/pdf';
// 设置pdf.worker.js文件的引入地址
PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/legacy/build/pdf.worker.entry.js');
// data是一个ArrayBuffer格式，也是一个buffer流的数据
let data = '123'
export default {
    data() {
        return {
            isDisabled: false,  //默认可以点击
            title: '返回',
            path: '', // 上一个页面的路径
            res: null, //响应文件流
            filename: '', //文件名
            loading: false, // 加载状态
            numPages: null, // pdf 页数
            fileData: null, //pdf ArrayBuffer
        }
    },
    mounted() { //不能在create里进行，因为那时候dom节点没有渲染好
        this.loading = true
        this.res = this.$route.params.res
        this.path = this.$route.params.path
        this.filename = this.$route.params.filename
        // console.log(this.$route.params)
        // console.log(this.res.data)
        if (this.filename.includes('.docx') || this.filename.includes('.doc')) { //word
            // console.log('word')
            let option = {
                className: 'docx', //默认和文档样式类的类名/前缀
                inWrapper: true, //启用围绕文档内容呈现包装器
                ignoreWidth: false, //禁用页面的渲染宽度
                ignoreHeight: false, //禁用页面的渲染高度
                ignoreFonts: false, //禁用字体渲染
                breakPages: true, //在分页符上启用分页
                ignoreLastRenderedPageBreak: true, //在lastRenderedPageBreak元素上禁用分页
                experimental: false, //启用实验功能（制表符停止计算）
                trimXmlDeclaration: true, //如果为true，则在解析之前将从xml文档中删除xml声明
                useBase64URL: false, //如果为true，图像、字体等将转换为base 64 URL，否则使用URL.createObjectURL
                useMathMLPolyfill: false, //包括用于铬、边等的MathML多填充。
                showChanges: false, //启用文档更改的实验渲染（插入/删除）
                debug: false, //启用额外的日志记录
            }
            docxx.renderAsync(this.res.data, this.$refs.word, null, option)
        } else if (this.filename.includes('.pdf')) { //pdf
            // 此处pdf的渲染数据this.fileData必须是一个ArrayBuffer格式的数据，如果请求的的数据是Blob格式必须要先使用Blob.arrayBuffer()转换
            // console.log('pdf')
            let reader = new FileReader();
            reader.readAsArrayBuffer(this.res.data)
            reader.onload = function() {
                this.fileData = reader.result
                data = reader.result
                // console.log(this.fileData)   
                // console.log(data) 
                        
            }
            setTimeout(() => {
                this.show()    
            }, 100)
        } else {
            this.loading =false
            return this.$message.error('暂不支持word、pdf以外的文件预览')
        }
        
        this.loading = false
    },
    methods: {
        renderPdfs(num, pdfDoc) {
            pdfDoc.getPage(num).then(page => {
                // 设置canvas相关的属性
                let pid = 'canvas_' + num
                // console.log(pid)
                const canvas = document.getElementById(pid);
                const ctx = canvas.getContext('2d');
                const dpr = window.devicePixelRatio || 1;
                const bsr =
                    ctx.webkitBackingStorePixelRatio ||
                    ctx.mozBackingStorePixelRatio ||
                    ctx.msBackingStorePixelRatio ||
                    ctx.oBackingStorePixelRatio ||
                    ctx.backingStorePixelRatio ||
                    1;
                const ratio = dpr / bsr;
                const viewport = page.getViewport({ scale: 1 });
                canvas.width = viewport.width * ratio;
                canvas.height = viewport.height * ratio;
                canvas.style.width = viewport.width + 'px';
                canvas.style.height = viewport.height + 'px';
                ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
                const renderContext = {
                    canvasContext: ctx,
                    viewport: viewport,
                };
                // 数据渲染到canvas画布上
                page.render(renderContext);
            })
        },
        show() {
            // console.log(data)
            PDFJS.getDocument(data).promise.then(pdfDoc => {
                this.numPages = pdfDoc.numPages; // pdf的总页数
                // 获取第1页的数据
                // console.log(this.numPages)
                for (let i = 1; i <= this.numPages; i++) {
                    // console.log(i);
                    this.renderPdfs(i, pdfDoc)
                }
                
            })
        },
        // pdf放大
        setPdfZoomin() {
            const max = 2;
            if (this.pdfScale >= max) {
                return;
            }
            this.pdfScale = this.pdfScale + 0.2;
            this.renderPdf();
        },
        // pdf缩小
        setPdfZoomout() {
            const min = 0.6;
            if (this.pdfScale <= min) {
                return;
            }
            this.pdfScale = this.pdfScale - 0.1;
            this.renderPdf();
        },

        download(FileName) {
            const blob = new Blob([this.res.data], {
                type: 'application/octet-stream'
            })
            const downloadElement = document.createElement('a')
            // 创建下载的链接
            // 兼容不同浏览器的URL对象
            const url = window.URL || window.webkitURL || window.moxURL;
            const href = url.createObjectURL(blob)
            // console.log(href)
            downloadElement.href = href
            // 下载后文件名
            downloadElement.download = FileName
            document.body.appendChild(downloadElement)
            // 点击下载
            downloadElement.click()
            // 下载完成移除元素
            document.body.removeChild(downloadElement)
            // 释放掉blob对象
            url.revokeObjectURL(href)
            //编译文件完成后，进度条展示为100%100
            this.percentage = 100;
            //下载完成 可以重新点击按钮下载
            this.isDisabled = false;
        },
        back() {
            let tab = this.$store.state.contentTabs[this.$store.state.contentTabs.length - 1];
            this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => {
                if (item.name === tab.name) {
                    return false;
                }
                return true;
            });
            // let tab1 = this.$store.state.contentTabs[this.$store.state.contentTabs.length - 1]
            // // console.log(tab)
            this.$router.push({
                // name: tab1.name,
                name: this.path,
                // params: { ...tab.params },
                // query: { ...tab.query }
            });
        }
    }
}
</script>
<style scoped>
div>button{
    margin: 10px 0;
}
</style>